<template>
	<view class="content">
		<view class="" v-if="!temState">
			
				<view class="fixed_head_box">
					<navBar
						@height="barHeight = $event"
						:themeColor="templateConfig.page.themeColor"
						:store="storeData"
						:padding="padding"
						ref="uniIndexedList"
					></navBar>
				</view>
			<view class="shop-content">
				<swiper
					class="swiper"
					:indicator-dots="true"
					:autoplay="true"
					:interval="3000"
					:duration="1000"
					:current="currentIndex"
					@change="changeSwiper"
					:style="{ marginTop: barHeight + 'px', height: swiperHeight + 'px' }">
				
					<swiper-item
						v-for="(item, index) in recommendedList"
						:key="index"
						@click="btnSwiper(index)"
					>
						<image
							class="swiper-img"
							:src="item.activityImgUrl"
							lazy-load="true"
							@load="loadImg"
							mode="widthFix"
						></image>
					</swiper-item>
				</swiper>

				<view class="category">
					<u-grid :border="false" col="4">
						<u-grid-item
							v-for="(item, index) in categoryList"
							@click="categoryItemTap(item)"
							:key="index"
							customStyle="margin-bottom: 20rpx"
						>
							<image class="grid-img" :src="item.icon" mode="aspectFill"></image>
							<text class="grid-text2">{{ item.categoryName }}</text>
						</u-grid-item>
						<u-grid-item v-if="templateConfig.overall.onesState==1" @click="Topath('/packageA/user/coupon/couponList')"  customStyle="margin-bottom: 20rpx">
							<image
							v-if="templateConfig.overall.textTwo==0"
								class="grid-img"
								src="https://oss.daccf.com/teei5jxcq4jjoke5y7jlr/活动/97036d85-ff4e-4586-b154-c83593339201.png"
								mode="aspectFill"
							></image>
							<image
								v-else
								class="grid-img"
								:src="templateConfig.overall.textTwo"
								mode="aspectFill"
							></image>
							<text class="grid-text2">优惠券</text>
						</u-grid-item>
						<u-grid-item v-if="templateConfig.overall.twoState==1" @click="Tocategory('/pages/category/category')" customStyle="margin-bottom: 20rpx">
							<view class="grid-img" style="display: flex;align-items: center;justify-content: center;" v-if="templateConfig.overall.textThree==0">
								<view class="iconfont" :class="['icon-fenlei2']"  :style="{ color: templateConfig.page.themeColor }"
									style="font-size: 50px;">
								</view>
							</view>
							<image
								v-else
								class="grid-img"
								:src="templateConfig.overall.textThree"
								mode="aspectFill"
							></image>
							<text class="grid-text2">更多分类</text>
						</u-grid-item>
					</u-grid>
				</view>

				<!-- 热销产品 -->
				<view class="cart-content">
					<view
						class="title"
						:class="scrollHeight > 600 ? 'fixed_head_box1' : ''"
						:style="{ top: scrollHeight > 600 ? barHeight + 'px' : '' }"
					>
						<view class="title-left" v-if="templateConfig.overall.textFour==0">本周热销</view>
						<view class="title-left" v-else>{{templateConfig.overall.textFour}}</view>
					</view>
					<view class="recommend-box">
						<view class="goods-block" v-for="(item, index) in goodsList" :key="index" :data-index="index">
							<view class="goods-box">
								<image
									class="goods-img"
									:src="item.rotationImgsJson[0]"
									mode="aspectFit"
									@click.native="navToDetailPage(item)"
								></image>
								<view class="goods-icon" v-if="item.videoUrl" @click.native="navToDetailPage(item)">
									<u-icon name="play-circle" color="#fff" size="28"></u-icon>
								</view>
								<view class="goods-name" @click.native="navToDetailPage(item)">
									{{ item.goodsName }}
								</view>
								<view class="goods-price">
									<view
										class="price"
										:style="{ color: templateConfig.page.themeColor }"
										@click.native="navToDetailPage(item)"
									>
										<view class="price-left" v-if="item.goodsSpecificationList == null">
											<text>￥</text>
											<text class="price-text">{{ item.goodsPrice }}</text>
										</view>
										<view class="price-left" v-else>
											<text>￥</text>
											<text class="price-text">
												{{ item.goodsSpecificationList[0].dealPrice }}
											</text>
										</view>
										<view class="price-right" v-if="item.scribePrice > 0">
											<text>￥</text>
											<text>{{ item.scribePrice }}</text>
										</view>
									</view>
									<u-icon
										name="shopping-cart"
										:color="templateConfig.page.themeColor"
										size="28"
										@click="addToCart(item)"
									></u-icon>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<tabbar
				:current="0"
				:cart="cartNums"
				:tabbarList="templateConfig.tabbarList"
				:template="templateConfig"
			></tabbar>
		</view>
		<view class="" v-else>
			<expire></expire>
		</view>
	</view>
</template>
<script>
import {
	getBusinessInfoList,
	getRecommen,
	getHomeDataInfo,
	getCategory,
	insertPlugsShopCart,
	userIsLogin,
	searchPlugsGoodsSpecificationByGoodsId,
	getPlugsShopCartByUserId,
	getUserTemplateConf,
	searchHotGoodsList,
	searchAdminUserById
} from '../../static/utils/api.js';
export default {
	data() {
		return {
			templateConfig: uni.getStorageSync('templateConfig'),
			temState: uni.getStorageSync('templateExpireTime'),
			goodsList: [], //热销商品
			categoryList: [],
			recommendedList: [],
			barHeight: 0,
			storeData: '',
			cartNums: 0,
			nowBusinessInfo: uni.getStorageSync('nowBusinessInfo'),
			scrollHeight: 0,
			background: {},
			adminInfo: {},
			swiperHeight: 0,
			currentIndex: 0
		};
	},
	async onLoad(option) {
		console.log(option,666);
		await this.$onLaunched;
		try {
			if (option.shareUserId) {
				uni.setStorageSync('shareUserId', option.shareUserId)
				if (option.goodsId) {
					uni.navigateTo({
						url: "/pages/index/detail?id="+ option.goodsId
					})
				}
			}
		} catch (error) {
			console.log(error);
		}
		
		this.nowBusinessInfo = uni.getStorageSync('nowBusinessInfo');
		this.storeData = this.nowBusinessInfo.businessName;
	},
	async onShow() {
		await this.$onLaunched;
		if (!uni.getStorageSync('nowBusinessInfo')) {
			this.getBusinessInfo();
		} else {
			this.nowBusinessInfo = uni.getStorageSync('nowBusinessInfo');
			this.templateConfig = uni.getStorageSync('templateConfig');
			this.storeData = this.nowBusinessInfo.businessName;
			this.cartNums = uni.getStorageSync('goodsNum') ? uni.getStorageSync('goodsNum') : 0;
			this.getTemplateConf();
			this.getAdminInfo();
			this.getswiperList();
			this.getCategoryList();
			this.getHomeDataInfo();
		}
	},

	onPageScroll(res) {
		this.scrollHeight = res.scrollTop;
	},

	onShareAppMessage() {
		console.log(123);
		let that = this;
		let path = 'pages/index/index';
		return {
			title: that.adminInfo.shareTitle != 0 ? that.adminInfo.shareTitle : that.storeData,
			imageUrl: that.adminInfo.shareImages != 0 ? that.adminInfo.shareImages : '',
			path: path+`?shareUserId=${uni.getStorageSync('userInfo').id}`,
		};
	},

	onShareTimeline() {
		let that = this;
		let path = 'pages/index/index';
		return {
			title: that.adminInfo.shareTitle != 0 ? that.adminInfo.shareTitle : that.storeData,
			imageUrl: that.adminInfo.shareImages != 0 ? that.adminInfo.shareImages : '',
			path: path,
			query:`shareUserId=${uni.getStorageSync('userInfo').id}`
			
		};
	},

	methods: {
		// 获取admin信息
		getAdminInfo() {
			let data = {
				id: uni.getStorageSync('userConfig').adminId
			};
			searchAdminUserById(data).then((res) => {
				this.adminInfo = JSON.parse(res.body.configJson);
				uni.setStorage({
					key: 'adminInfo',
					data: this.adminInfo
				});
				
			});
		},
		getTemplateConf() {
			const userConfig = uni.getStorageSync('userConfig');
			let params = {
				userServiceToken: this.userToken
			};
			getUserTemplateConf(params).then((res) => {
				if (res.code == 200 && res.body) {
					let data = res.body.templateConf.templateConfJson;
					let newData = res.body.templateSettingsJson;
					if (res.body.templateConf.templateConfJson) {
						uni.setStorage({
							key: 'templateConfig',
							data: JSON.parse(res.body.templateConf.templateConfJson)
						});
					} else {
						uni.setStorage({
							key: 'templateConfig',
							data: JSON.parse(res.body.templateSettingsJson)
						});
					}
				}
			});
		},
		getBusinessInfo() {
			let data = {
				latitude: 0,
				longitude: 0
			};
			getBusinessInfoList(data).then((res) => {
				if (res.code == 200) {
					this.BusinessInfoList = res.body;
					this.nowBusinessInfo = this.BusinessInfoList[0].jsonViewData;
					this.storeData = this.nowBusinessInfo.businessName;
					uni.setStorage({
						key: 'nowBusinessInfo',
						data: this.nowBusinessInfo
					});
					this.templateConfig = uni.getStorageSync('templateConfig');
					this.getAdminInfo();
					this.getTemplateConf();
					this.getswiperList();
					this.getCategoryList();
					this.getHomeDataInfo();

					// this.getCartList()
				}
			});
		},
		// 获取轮播
		getswiperList() {
			let data = {
				businessId: this.nowBusinessInfo.businessId.toString()
			};
			getRecommen(data).then((res) => {
				if (res.code == 200) {
					let arr1 = [];
					let arr2 = [];
					let arr3 = [];
					let arr4 = [];
					let arr5 = [];
					arr1 = res.body.filter((itm) => itm.type === 'homeData');
					arr2 = res.body.filter((itm) => itm.type === 'homeProgram');
					arr3 = res.body.filter((itm) => itm.type === 'homePages');
					arr4 = res.body.filter((itm) => itm.type === 'homeAccount');
					arr5 = res.body.filter((itm) => itm.type === 'homeShop');
					this.recommendedList = [...arr1, ...arr2, ...arr3, ...arr4, ...arr5];
				}
			});
		},

		loadImg() {
			this.setSwiperHeight('.swiper-img');
		},

		changeSwiper(e) {
			this.currentIndex = e.detail.current;
			//动态设置swiper的高度，使用nextTick延时设置
			this.$nextTick(() => {
				this.setSwiperHeight('.swiper-img');
			});
		},
		// 获取轮播高度
		setSwiperHeight(element) {
			console.log(99999);
			let query = uni.createSelectorQuery().in(this);
			query.selectAll(element).boundingClientRect();
			query.exec((res) => {
				if (this.recommendedList.length && res[0][this.currentIndex].height) {
					this.swiperHeight = res[0][this.currentIndex].height;
				}
			});
		},

		btnSwiper(index) {
			console.log(this.recommendedList[index]);
			if (this.recommendedList[index].type == 'homePages') {
				uni.navigateTo({
					url: `${this.recommendedList[index].detailsImgAndPageUrl}`
				});
			} else if (this.recommendedList[index].type == 'homeAccount') {
				uni.navigateTo({
					url: '/packageA/index/account?url=' + this.recommendedList[index].detailsImgAndPageUrl
				});
			} else if (this.recommendedList[index].type == 'homeShop') {
				uni.navigateTo({
					url: `/pages/index/detail?id=${this.recommendedList[index].detailsId}`
				});
			} else if (this.recommendedList[index].type == 'homeProgram') {
				wx.navigateToMiniProgram({
					appId: this.recommendedList[index].detailsImgAndPageUrl,
					path: '/pages/index/index',
					//develop开发版；trial体验版；release正式版
					envVersion: 'release',
					success(res) {
						// 打开成功
						console.log('跳转小程序成功！', res);
					}
				});
			}
		},

		// 获取分类数据
		getCategoryList() {
			let data = {
				businessId: this.nowBusinessInfo.businessId.toString(),
				pid: 0
			};
			getCategory(data).then((res) => {
				if (res.code == 200) {
					this.categoryList = [];
					for (let i = 0; i < res.body.list.length; i++) {
						if (i > 5) {
							break;
						} else {
							this.categoryList.push(res.body.list[i]);
							// this.categoryList = res.body.list
						}
					}
				}
			});
		},
		// 获取热门数据
		getHomeDataInfo() {
			let data = {
				businessId: this.nowBusinessInfo.businessId.toString(),
				recommendationStatus: 1,
				size: 100
			};

			searchHotGoodsList(data).then((res) => {
				if (res.code == 200) {
					res.body.list.forEach((item) => {
						if (item.rotationImgsJson) {
							item.rotationImgsJson = JSON.parse(item.rotationImgsJson);
						}
					});
					this.goodsList = res.body.list;
				}
			});
		},
		// 去商品详情
		navToDetailPage(item) {
			//测试数据没有写id，用title代替
			let id = item.id;
			uni.navigateTo({
				url: `/pages/index/detail?id=${id}`
			});
		},
		// 获取当前店铺购物车数量
		getCartList() {
			let data = {
				page: 1,
				size: 100,
				businessId: this.nowBusinessInfo.businessId.toString(),
				userServiceToken: this.userToken
			};
			getPlugsShopCartByUserId(data).then((res) => {
				if (res.code === 200) {
					// let nums = 0;
					// res.body.list.forEach(item => {
					// 	nums += item.goodsNum;
					// })
					// this.cartNums = nums;
					this.cartNums = res.body.total;
				}
			});
		},
		// 加入购物车
		addToCart(item) {
			let token = uni.getStorageSync('userInfo').accessToken;
			if (token == null) {
				uni.showModal({
					title: '提示',
					content: '登录才能添加宝贝哦~',
					success: function (res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/user/login'
							});
						} else if (res.cancel) {
						}
					}
				});
			} else {
				searchPlugsGoodsSpecificationByGoodsId({
					goodsId: item.id
				}).then((res) => {
					if (res.code == 200) {
						if (res.body.plugsGoodsSpecificationList.length == 0) {
							let postData = {
								businessId: this.nowBusinessInfo.businessId.toString(),
								goodsId: item.id,
								goodsCategoryId: item.categoryId,
								goodsNum: 1,
								goodsSpecificationIds: '0'
							};
							if (item.stockNum <= 0) {
								uni.showModal({
									title: '提示',
									content: '库存不足!',
									showCancel: false
								});
								return;
							}
							item.stockNum--;
							insertPlugsShopCart(postData).then((res) => {
								if (res.code == 200) {
									uni.showToast({
										title: '加入成功',
										icon: 'none'
									});
									this.getCartList();
								} else {
									item.stockNum++;
								}
							});
						} else {
							let postData = {
								businessId: this.nowBusinessInfo.businessId.toString(),
								goodsId: item.id,
								goodsCategoryId: item.categoryId,
								goodsNum: 1,
								goodsSpecificationIds: res.body.plugsGoodsSpecificationList[0].id
							};
							if (res.body.plugsGoodsSpecificationList[0].stockNum <= 0) {
								uni.showModal({
									title: '提示',
									content: '库存不足!',
									showCancel: false
								});
								return;
							}
							res.body.plugsGoodsSpecificationList[0].stockNum--;
							insertPlugsShopCart(postData).then((res) => {
								if (res.code == 200) {
									uni.showToast({
										title: '加入成功',
										icon: 'none'
									});
									this.getCartList();
								} else {
									res.body.plugsGoodsSpecificationList[0].stockNum++;
								}
							});
						}
					}
				});
			}
		},
		// 跳转
		Topath(route) {
			uni.navigateTo({
				url: route
			});
		},
		Tocategory(route) {
			uni.switchTab({
				url: route
			});
		},
		// 去分类页面
		categoryItemTap(item) {
			uni.navigateTo({
				url: `/pages/index/category?id=${item.id}&&name=${item.categoryName}`
			});
		}
	}
};
</script>

<style lang="less">
page {
	background-color: white;
}

.content {
	width: 100%;
	display: flex;
	overflow-x: hidden;
	flex-direction: column;
	justify-content: center;
	position: relative;
	.fixed_head_box {
		width: 100%;
		background-color: #fff;
		position: fixed;
		top: 550;
		left: 0;
		z-index: 100;
	}

	.fixed_head_box1 {
		width: 100%;
		background-color: #fff;
		position: fixed;
		top: 175rpx;
		left: 30rpx;
		z-index: 100;
	}
	
	.shop-content{
		display: flex;
		flex-direction: column;
		.swiper {
			padding: 0 20rpx;
			.swiper-img {
				border-radius: 15rpx;
			}
		}
		
		.category {
			padding: 40rpx 0 0rpx;
			box-sizing: border-box;
			display: flex;
		
			.grid-img {
				width: 100rpx;
				height: 100rpx;
				border-radius: 16rpx;
			}
		
			.grid-text2 {
				margin-top: 12rpx;
				font-size: 26rpx;
			}
		}
		
		.cart-content {
			flex: 1;
			padding: 20rpx 30rpx;
			background-color: #fff;
			border-radius: 20rpx;
		
			.title {
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 80rpx;
		
				.title-left {
					font-size: 36rpx;
					font-weight: 700;
				}
		
				.title-right {
					display: flex;
					align-items: center;
					font-size: 30rpx;
					font-weight: 700;
				}
			}
		
			.recommend-box {
				width: 100%;
				display: flex;
				justify-content: space-between;
				flex-wrap: wrap;
		
				.goods-block {
					width: 48%;
				}
		
				.goods-box {
					width: 100%;
					height: 470rpx;
					border-radius: 16rpx;
					box-sizing: border-box;
					background-color: #fff;
					margin-bottom: 20rpx;
					border: 3rpx solid #f5f5f5;
					position: relative;
					.goods-img {
						width: 330rpx;
						height: 330rpx;
						border-radius: 16rpx 16rpx 0 0;
					}
					.goods-icon {
						position: absolute;
						top: 10rpx;
						right: 10rpx;
					}
					.goods-name {
						width: 94%;
						margin: 10rpx auto;
						font-size: 28rpx;
						display: -webkit-box; //将对象作为弹性伸缩盒子模型显示
						-webkit-box-orient: vertical; //设置或检索伸缩盒对象的子元素的排列方式
						-webkit-line-clamp: 1; //一个块元素显示的文本的行数
						overflow: hidden; //溢出隐藏
					}
		
					.goods-price {
						width: 94%;
						margin: auto;
						display: flex;
						align-items: center;
						justify-content: space-between;
		
						.price {
							color: #ff4544;
							display: flex;
							align-items: center;
		
							.price-text {
								font-size: 34rpx;
								font-weight: 600;
							}
		
							.price-right {
								margin-left: 12rpx;
								font-size: 26rpx !important;
								font-weight: 400 !important;
								color: #aaa;
								margin-left: 18rpx;
								text-decoration: line-through;
							}
						}
					}
				}
			}
		}
	}
	
	
}
</style>
